import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:seedfour/app/models/file_list_entity.dart';
import 'package:seedfour/app/routes/app_routes.dart';
import 'package:seedfour/app/services/common_service.dart';

import '../../models/raw_data.dart';
import '../../services/api_service.dart';

class FolderListLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = true.obs;
  var bottomTips = ''.obs;
  var files = <FileData>[].obs;

  // 添加下载进度相关状态
  var downloadingFileId = ''.obs;
  var downloadProgress = 0.0.obs;

  final scrollController = ScrollController();

  late FileData? parentFolder;
  late String title;

  final pageSize = 10;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        // _getFolderList();
      }
    });

    parentFolder = Get.arguments;
    title = '文件盘${parentFolder == null ? '' : ' / ${parentFolder!.name}'}';

    _reload();
  }

  void toFileList(int index) {
    if (files[index].fileId != null) {
      return;
    }
    Get.toNamed(RouteGet.folderList,
        arguments: files[index], preventDuplicates: false);
  }

  void toFileSearch() {
    Get.toNamed(RouteGet.fileSearch);
  }

  void downloadFile(FileData file) async {
    downloadingFileId.value = file.fileId.toString();
    downloadProgress.value = 0.0;

    Directory? appDocDir = await getDownloadsDirectory();
    String savePath = '${appDocDir!.path}/${file.fileName}';

    RawData? result = await apiService.download(file.fileId!, file.caseId!,
        type: 'dir-delivery');

    if (result != null) {
      var url = result.value['data']['tempPath'];
      try {
        final response = await Dio().download(
          url,
          savePath,
          onReceiveProgress: (received, total) {
            if (total != -1) {
              downloadProgress.value = received / total;
              EasyLoading.showProgress(downloadProgress.value,
                  status:
                      '下载中... ${((downloadProgress.value) * 100).toStringAsFixed(0)}%');
            }
          },
        );

        if (response.statusCode == 200) {
          EasyLoading.showToast('文件已保存到：$savePath',
              duration: const Duration(seconds: 6));
        } else {
          EasyLoading.showToast('下载失败');
        }
      } catch (e) {
        EasyLoading.showToast('下载失败：$e');
      } finally {
        downloadingFileId.value = '';
        downloadProgress.value = 0.0;
      }
    }
  }

  void _reload() {
    _page = 1;
    files.clear();
    _getFolderList();
  }

  void _getFolderList() {
    apiService
        .getFileList(_page, pageSize, commonService.getRole(),
            folderId: (parentFolder == null ? '' : parentFolder!.caseId))
        .then((folder) => {
              isLoading.value = false,
              _page++,
              if (folder != null)
                {
                  files.addAll(folder.data ?? []),
                  if (folder.data!.length < pageSize)
                    {bottomTips.value = '${folder.total} 个文件夹'}
                  else
                    {bottomTips.value = loadingTip}
                }
              else
                {bottomTips.value = noMoreTip}
            });
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }
}
